package com.hcrazy.manchester.app.services;

import java.lang.reflect.Type;
import java.util.List;

import org.joda.time.DateTime;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hcrazy.manchester.app.jdbc.CouponSellerDAO;
import com.hcrazy.manchester.app.pojo.CouponAddress;
import com.hcrazy.manchester.app.pojo.CouponSeller;
import com.hcrazy.manchester.app.pojo.ErrorMsg;
import com.hcrazy.manchester.app.pojo.PageModel;
import com.hcrazy.manchester.app.utils.Constant;

public class CouponSellerService {

	private CouponSellerDAO couponSellerDAO;
	
	public CouponSellerDAO getCouponSellerDAO() {
		return couponSellerDAO;
	}

	public void setCouponSellerDAO(CouponSellerDAO couponSellerDAO) {
		this.couponSellerDAO = couponSellerDAO;
	}

	public ErrorMsg addOrUpdateCouponSeller(CouponSeller seller) throws Exception{
		ErrorMsg msg = new ErrorMsg();
		msg.setCode(Constant.SUCCESS);//success
		int sellerId = 0;
		DateTime dt = new DateTime();
		String date = dt.toString("yyyy-MM-dd HH:mm:ss");
		
		seller.setUpdateDate(date);
		
		if(seller.getSellerId()>0){
			seller.setCreateDate(date);
			couponSellerDAO.updateCouponSeller(seller);
			sellerId = seller.getSellerId();
			//批量删除地址信息
			couponSellerDAO.deleteAddreses(sellerId);
		}else{
			sellerId = couponSellerDAO.addCouponSeller(seller);
		}
		
		//批量添加地址信息
		Gson gson = new Gson();
		Type type = new TypeToken<List<CouponAddress>>(){}.getType();
		List<CouponAddress> addresses = gson.fromJson(seller.getAddresses(),type);
		
		couponSellerDAO.addAddresses(addresses, sellerId);
		return msg;
	}
	
	public PageModel getCouponSellers(PageModel model,String search,int sortId) throws Exception{
		PageModel pageModel = couponSellerDAO.getPagedInfos(model, search, sortId);
		
		return pageModel;
	}
	
	public CouponSeller getCouponSellerById(int sellerId) throws Exception{
		CouponSeller seller = couponSellerDAO.getById(sellerId);
		List<CouponAddress> details = couponSellerDAO.getAddressesBySellerId(sellerId);

		// 将对象转化为json字符串
		Gson gson = new Gson();
		Type type = new TypeToken<List<CouponAddress>>(){}.getType();
		seller.setAddresses(gson.toJson(details, type));
		
		return seller;
	}
	
	public List<CouponAddress> getAddressesBySellerId(int sellerId) throws Exception {
		
		List<CouponAddress> details = couponSellerDAO.getAddressesBySellerId(sellerId);
		
		return details;
	}
	
	public List<CouponSeller> getAllConponSellersBySortId(int sortId) throws Exception{
		return couponSellerDAO.getAllInfosBySortId(sortId);
	}
	
	public void delCouponSeller(int sellerId) throws Exception{
		couponSellerDAO.delCouponSeller(sellerId);
	}
}
